<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/3/13
 * Time: 20:48
 */

namespace app\cls\tom;


class Encrypt
{
    private static $key = "587964321";//key中不能有__

    /**
     * 编码
     * @param string $string
     * @return mixed
     */
    public static function encode($string = '') {
        $string = $string."__".md5($string.static::$key);
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split(static::$key) as $key => $value)
            $key < $strCount && $strArr[$key].=$value;
        return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
    }

    /**
     * 解码
     * @param string $string
     * @return bool|string
     */
    public static  function decode($string = '') {
        $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
        $strCount = count($strArr);
        foreach (str_split(static::$key) as $key => $value)
            $key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        $str =  base64_decode(join('', $strArr));
        if($str){
            $arr = explode("__",$str);
            if(count($arr) != 2){
                return "";
            }
            if(md5($arr[0].static::$key) != $arr[1]){
                return "";
            }
            return $arr[0];
        }else{
            return "";
        }
    }
}